/*
 * DBAccess.cpp
 *
 *  Created on: 07-Nov-2014
 *      Author: ali
 */

#include "DBAccess.h"
#include <string.h>

DBAccess::DBAccess(const char* dbname) :
		m_db(0)
{
	if (NULL != dbname)
	{
		Open(dbname);
	}
}
int DBAccess::Open(const char* dbname)
{
	int rc = SQLITE_OK;
	if (NULL == m_db)
	{
		rc = sqlite3_open(dbname, &m_db);
		if (rc != SQLITE_OK)
		{
			throw DBAccess_error("can't connect database");
		}
	}
	return rc;
}
int DBAccess::Close()
{
	int rc = SQLITE_OK;
	if (m_db)
	{
		rc = sqlite3_close(m_db);
		m_db = 0;
	}
	return rc;
}
int DBAccess::Exec(const char* sql)
{
#if 0
	sqlite3_stmt *stmt = NULL;
	sqlite3_prepare(m_db, sql, strlen(sql), &stmt, NULL);
	rc = sqlite3_step(stmt);
	if (rc != SQLITE_DONE)
	{
		cout << "Didn't exec query. Cause " << sqlite3_errmsg(m_db)<< endl;
	}
	if (NULL != stmt)
	{
		rc = sqlite3_finalize(stmt);
	}
	return rc;
#endif
	return sqlite3_exec(m_db, sql, 0, 0, 0);
}

int DBAccess::ExecInsert(const char* sql)
{
	int rc = SQLITE_OK;
	cout << "Creating Statement" << endl;
	sqlite3_stmt *stmt = NULL;
	sqlite3_prepare(m_db, sql, strlen(sql), &stmt, NULL);
	rc = sqlite3_step(stmt);
	if (rc != SQLITE_DONE)
	{
		cout << "SQL Statement: "<< sql <<" Failed. Cause " << sqlite3_errmsg(m_db) << endl;
	}
	if (NULL != stmt)
	{
		rc = sqlite3_finalize(stmt);
	}
	return rc;
}
int DBAccess::ExecCommand(const char* sql)
{
	int rc = SQLITE_OK;
	cout << "Creating Command Statement" << endl;
	sqlite3_stmt* stmt = NULL;
	sqlite3_prepare_v2(m_db, sql, strlen(sql), &stmt, NULL);
	rc = sqlite3_step(stmt);
	if (rc != SQLITE_DONE)
	{
		cout << "SQL Statement: "<< sql <<" Failed. Cause " <<
				sqlite3_errmsg(m_db) << endl;
	}
	if (NULL != stmt)
	{
		rc = sqlite3_finalize(stmt);
	}
	return rc;
}
DBAccess::~DBAccess()
{
	Close();
}
DBAccess_error::DBAccess_error(char const* msg) :
		std::runtime_error(msg)
{
}

DBAccess_error::DBAccess_error(DBAccess& db) :
		std::runtime_error(sqlite3_errmsg(db.m_db))
{
}
